package com.yiqi.liebang.feature.mine.view;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnDismissListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.Gson;
import com.suozhang.framework.component.http.RxDataProcessFactory;
import com.suozhang.framework.framework.AM;
import com.suozhang.framework.framework.BaseActivity;
import com.suozhang.framework.utils.DateUtil;
import com.suozhang.framework.utils.T;
import com.yiqi.liebang.R;
import com.yiqi.liebang.common.util.DateTool;
import com.yiqi.liebang.common.util.GetJsonDataUtil;
import com.yiqi.liebang.entity.bo.EditBithBo;
import com.yiqi.liebang.entity.bo.JsonBean;
import com.yiqi.liebang.framework.api.UserApi;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

import static com.suozhang.framework.utils.DateUtil.formatTimeToState2;
import static com.yiqi.liebang.common.util.DateTool.DEFAULT_NYR;
import static com.yiqi.liebang.common.util.DateTool.DEFAULT_YR;

public class EditOtherActivity extends BaseActivity implements Toolbar.OnMenuItemClickListener {
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.tv_edit_other_city)
    TextView mTvEditOtherCity;
    @BindView(R.id.tv_edit_other_date)
    TextView mTvEditOtherDate;

    private List<JsonBean> options1Items = new ArrayList<>();
    private List<List<String>> options2Items = new ArrayList<>();
    private List<List<List<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;

    private boolean isLoaded = false;

    private String dateStr;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_edit_other;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initView() {
        mToolbar.inflateMenu(R.menu.menu_save);
        initToolBar(mToolbar, "编辑其他信息", true, true);
        mToolbar.setOnMenuItemClickListener(this);
    }

    @Override
    protected void initData() {
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        String home = getIntent().getStringExtra("home");
        dateStr = getIntent().getStringExtra("bith");
        mTvEditOtherCity.setText(TextUtils.isEmpty(home) ? "" : home);
        mTvEditOtherDate.setText(TextUtils.isEmpty(dateStr) ? "" : formatTimeToState2(dateStr));
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
//                        Toast.makeText(EditOtherActivity.this, "Begin Parse Data", Toast.LENGTH_SHORT).show();
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
//                    Toast.makeText(EditOtherActivity.this, "Parse Succeed", Toast.LENGTH_SHORT).show();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    Toast.makeText(EditOtherActivity.this, "Parse Failed", Toast.LENGTH_SHORT).show();
                    finish();
                    break;
            }
        }
    };

    @OnClick({R.id.btn_edit_other_city, R.id.tv_edit_other_date})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_edit_other_city:
                if (isLoaded) {
                    showPickerView();
                } else {
                    T.showShort("Please waiting until the data is parsed");
                }
                break;
            case R.id.tv_edit_other_date:

                TimePickerView pvEnd = new TimePickerBuilder(this, null,new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        dateStr=DateTool.date2String(date, DEFAULT_NYR);
                        mTvEditOtherDate.setText(DateTool.date2String(date, DEFAULT_YR));

                    }

                    @Override
                    public void onTimeZhijin(Date date, View v) {

                    }
                })
                        .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                        .setLineSpacingMultiplier(1.8f)
                        .build();
                pvEnd.show();

                break;

        }
    }



    private void showPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText() +
                        options2Items.get(options1).get(options2);
                mTvEditOtherCity.setText(tx);

            }
        })

                .setTitleText("城市选择")
                .setDividerColor(R.color.div_primary)
                .setLineSpacingMultiplier(2.5f)
                .setTextColorCenter(R.color.text_primary) //设置选中项文字颜色
                .setContentTextSize(15)
                .build();


        pvOptions.setPicker(options1Items, options2Items);//三级选择器
        pvOptions.show();
    }

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        List<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体


        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            List<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            List<List<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市
                List<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {
                    City_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public List<JsonBean> parseData(String result) {//Gson 解析
        List<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    private void edit(String home, String bithday) {
        if (TextUtils.isEmpty(home)) {
            T.showShort("请选择家乡！");
            return;
        }

        if (TextUtils.isEmpty(bithday)) {
            T.showShort("请选择生日！");
            return;
        }


        AM.api().createApiService(UserApi.class).editBithday(new EditBithBo(home, bithday))
                .compose(RxDataProcessFactory.dataPrepAndIoToMainTransformer())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String s) {
//                        showMsg("修改成功！");
                        finish();
                    }

                    @Override
                    public void onError(Throwable e) {
                        showMsg("" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        edit(mTvEditOtherCity.getText().toString(), dateStr);
        return false;
    }
}
